package me.numark.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.logging.Handler;
import java.util.logging.LogRecord;

import butterknife.Bind;
import me.numark.R;
import me.numark.activities.ChatActivity;
import me.numark.activities.FansActivity;
import me.numark.activities.FollowsActivity;
import me.numark.activities.SettingsActivity;
import me.numark.model.ProfileResponse;
import me.numark.model.User;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.LogUtils;
import me.numark.view.CircleImageView;
import me.numark.view.PagerSlidingTabStrip;

/**
 * Created by Evan on 15/7/26.
 */
public class ProfileFragment extends BaseFragment implements AppBarLayout.OnOffsetChangedListener,
        View.OnClickListener, ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, View.OnTouchListener {

    @Bind(R.id.avatar)
    CircleImageView avatar;

    @Bind(R.id.name)
    TextView name;

    @Bind(R.id.follow_count)
    TextView follows;

    @Bind(R.id.fans_count)
    TextView fans;

    @Bind(R.id.ff_line)
    View followInfoView;

    @Bind(R.id.tab_switcher)
    View tabSwitcher;

    @Bind(R.id.profile_toolbar)
    View profileToolbar;

    @Bind(R.id.follow)
    Button followBtn;

    @Bind(R.id.msg)
    Button msgBtn;

//    @InjectView(R.id.follow_label)
//    TextView follows_label;
//
//    @InjectView(R.id.fans_label)
//    TextView fans_label;

    @Bind(R.id.desc)
    TextView desc;

    @Bind(R.id.viewpager)
    ViewPager pager;

   /* @Bind(R.id.radio_left)
    RadioButton leftRadio;

    @Bind(R.id.radio_right)
    RadioButton rightRadio;
*/
    @Bind(R.id.left_divider)
    View divider;

    @Bind(R.id.show_tabs)
    PagerSlidingTabStrip tabs;

    /*@Bind(R.id.radio_center)
    @Nullable
    RadioButton centerRadio;*/

   /* @Bind(R.id.radio_group)
    RadioGroup radioGroup;*/

    @Bind(R.id.right_image)
    ImageView rightImage;

    /*@Bind(R.id.appBarLayout)
    AppBarLayout appBarLayout;*/

   /* @Bind(R.id.coordinator)
    CoordinatorLayout mCoordinatorLayout;*/

    @Bind(R.id.coordinator)
    CollapsingToolbarLayout mCoordinatorLayout;

    @Bind(R.id.follow_layout)
    FrameLayout followLayout;

    @Bind(R.id.follow_text)
    TextView txtFollow;

    @Bind(R.id.fans_text)
    TextView txtFans;
    public static final String LOG_TAG = ProfileFragment.class.getSimpleName();

    BaseListFragment[] fragments;

    ProfilePageAdapter mAdapter;

    public static final String USER_ID = "user_id";
    private int mUserId;

    private boolean isMe;
    private boolean isPrivate;

    private User mUser;

    @Override
    public void onResume() {
        super.onResume();
       // appBarLayout.addOnOffsetChangedListener(this);
        if (isMe)
            refresh();
    }

    @Override
    public void onPause() {
        super.onPause();
       // appBarLayout.removeOnOffsetChangedListener(this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);

        mUserId = getArguments() == null ? Global.getCurrentUid()
                : getArguments().getInt(USER_ID, -1);
        isMe = mUserId == Global.getCurrentUid();
        isPrivate = (mUserId == -1)||(mUserId == 1);
        fragments = new BaseListFragment[1];

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mCoordinatorLayout.setOnTouchListener(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user_profile, container, false);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        avatar.setBorderWidth(2);
        avatar.setBorderColor(Global.avatarColor);
        rightImage.setVisibility(View.VISIBLE);
        backInToolbar.setOnClickListener(this);

        if (isMe) {
            titleTextView.setText(R.string.profile);
            rightImage.setImageResource(R.drawable.action_bar_settings_1);
            rightImage.setOnClickListener(this);
            profileToolbar.setVisibility(View.GONE);
        } else {
            //name.setVisibility(View.VISIBLE);
        }
        if (isPrivate) {
            if (mUserId == -1) {
                tabSwitcher.setVisibility(View.GONE);
                profileToolbar.setVisibility(View.GONE);
                followInfoView.setVisibility(View.GONE);
            }
            if (mUserId == 1){
                tabSwitcher.setVisibility(View.GONE);
                followInfoView.setVisibility(View.GONE);
                followLayout.setVisibility(View.GONE);
                divider.setVisibility(View.GONE);
            }
        }
        fans.setOnClickListener(this);
        follows.setOnClickListener(this);
        msgBtn.setOnClickListener(this);
        followBtn.setOnClickListener(this);
        mAdapter = new ProfilePageAdapter();
       /* if (Constants.ENABLE_CLICK_APPLAYOUT)
            appBarLayout.setOnClickListener(this);*/
        pager.setAdapter(mAdapter);
        pager.addOnPageChangeListener(this);


        tabs.setVisibility(View.GONE);
        tabs.setShouldExpand(true);
        tabs.setIndicatorColorResource(R.color.btn_green);
        tabs.setUnderlineColorResource(R.color.transparent);
        tabs.setCheckedTextColorResource(R.color.btn_green);
        tabs.setViewPager(pager);
        //radioGroup.setOnCheckedChangeListener(this);
        onPageSelected(0);
    }

    void updateFollowBtn() {
        LogUtils.d(LOG_TAG, "isFollow:" + mUser.is_follow + " isFans:" + mUser.is_fans);
        if (!mUser.is_fans) {
            followBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.follow_follow, 0, 0, 0);
            followBtn.setText(R.string.follow);
        } else {
            if (mUser.is_fans)
            {
                followBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.follow_followed, 0, 0, 0);
                followBtn.setText(R.string.cancel_followed);
                if (mUser.is_follow) {
                    followBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.follow_both, 0, 0, 0);
                    followBtn.setText(R.string.follow_both);
                }
            }
        }
    }

    @Override
    protected void bindData(BaseResponse response, boolean isNew) {
        super.bindData(response, isNew);
        ProfileResponse resp = (ProfileResponse) response;
        mUser = resp.data;
        fans.setText(String.valueOf(mUser.fans));
        follows.setText(String.valueOf(mUser.follow));

        if (!isMe) {
            titleTextView.setText(mUser.nick);
            txtFans.setText(getString(R.string.his_fans));
            txtFollow.setText(getString(R.string.his_follow));
        }else {
            txtFans.setText(getString(R.string.my_fans));
            txtFollow.setText(R.string.my_follow);
        }
        name.setText(mUser.nick);
        desc.setText(mUser.des);
        updateFollowBtn();
        if (mUser.pic!=null) {
            Picasso.with(getActivity()).load(mUser.pic).into(avatar);
        }else {
            avatar.setImageResource(R.drawable.avatar_bg_normal);
        }
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, ProfileResponse.class);
    }

    @Override
    protected String cacheKey() {
        return "user_" + mUserId;
    }

    @Override
    public void refresh() {
        if (isMe) {
            mUserId = Global.getCurrentUid();
            if (mUserId == 0)
                return;
        }
        super.refresh();
        String loading = null;
        if (mUser == null)
            loading = getString(R.string.refreshing_profile);
        new RequestServerTask<ProfileResponse>(ProfileResponse.class, this, loading) {
            @Override
            protected String requestServer() {
                String url = String.format(NetworkConstants.PROFILE_URL, mUserId);
                return HttpUtil.get(url, null);
            }

            @Override
            protected void onSuccess(ProfileResponse result) {
                bindData(result, true);
            }
        }.start();
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
        for (BaseListFragment fragment : fragments) {
            if (fragment != null)
                fragment.enableRefresh(offset == 0);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                getActivity().finish();
                break;
            case R.id.right_image:
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                break;
            case R.id.follow:
                doFollow();
                break;
            case R.id.follow_text:
            case R.id.follow_count:
                Intent intent = new Intent(getActivity(), FollowsActivity.class);
                intent.putExtra(USER_ID, mUserId);
                startActivity(intent);
                break;
            case R.id.fans_text:
            case R.id.fans_count:
                Intent intent1 = new Intent(getActivity(), FansActivity.class);
                intent1.putExtra(USER_ID, mUserId);
                startActivity(intent1);
                break;
            case R.id.msg:
                ChatActivity.startChat(getActivity(), mUser);
                break;
        }
    }

    void doFollow() {
        int msg = mUser.is_fans ? R.string.submit_unfollow : R.string.submit_follow;
        new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(msg)) {
            @Override
            protected String requestServer() {
                String baseUrl = mUser.is_fans ? NetworkConstants.UNFOLLOW_URL : NetworkConstants.FOLLOW_URL;
                String url = String.format(baseUrl, Global.getCurrentUid(), mUser.uid);
                return HttpUtil.get(url, null);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                mUser.is_fans = !mUser.is_fans;
                //updateFollowBtn();
                mBaseFragmentReceiver.onReceive(getActivity(), new Intent(Constants.ACTION_USER_CHANGED));
            }
        }.setSnackbarView(rootView).start();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.radio_right) {
            pager.setCurrentItem(1);
        } /*else if (checkedId == R.id.radio_center) {
            pager.setCurrentItem(1);
        }*/ else {
            pager.setCurrentItem(0);
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {
        tabs.onPageScrolled(i,v, i1);
    }

    @Override
    public void onPageSelected(int i) {
        /*if (i == 2) {
            radioGroup.check(R.id.radio_right);
        } else if (i == 1) {
            radioGroup.check(R.id.radio_center);
        } else {
            radioGroup.check(R.id.radio_left);
        }*/
        tabs.onPageSelected(i);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        tabs.onPageScrollStateChanged(state);
    }

   /* void hideTopPanel() {
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        int offset = behavior.getTopAndBottomOffset();
        if (offset == 0) {
            behavior.onNestedFling(mCoordinatorLayout, appBarLayout, null, 0, Integer.MAX_VALUE, true);
        } else {
            behavior.setTopAndBottomOffset(0);
        }
    }*/

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }

    private class ProfilePageAdapter extends FragmentPagerAdapter {

        public ProfilePageAdapter() {
            super(getChildFragmentManager());
        }

        public String getPageTitle(int i){
            String title = null;
            switch (i){
                case 0:
                    title = "推荐";
                    break;
                /*case 1:
                    title = "评论";
                    break;*//*
                case 1:
                    title = "赞";
                    break;*/

            }
            return title;
        }
        @Override
        public Fragment getItem(int i) {
            if (fragments[i] == null) {
                switch (i) {
                    case 0:
                        fragments[0] = FeedFragment.newInstance(Constants.FEEDTYPE_USER_MARKS, mUserId);
                        break;
                   /* case 1:
                        fragments[1] = FeedFragment.newInstance(Constants.FEEDTYPE_USER_COMMENTS, mUserId);
                        break;*/
                   /* case 1:
                        fragments[1] = FeedFragment.newInstance(Constants.FEEDTYPE_USER_LIKES, mUserId);
                        break;*/
                }
            }

            return fragments[i];
        }

        @Override
        public int getCount() {
            if (isPrivate)
                return 1;
            return 1;
        }
    }
}
